package models


type UserQuestion struct {
	Id           int `json:"id" xorm:"not null pk autoincr comment('主键') INT(11)"`
	UserId int `json:"user_id" xorm:"not null comment('用户id')  INT(11)"`
	QuestionId int `json:"question_id" xorm:"not null comment('题目主键') INT(11)"`
	TestStatus int `json:"test_status" xorm:"not null comment('做题情况') INT(11)"`
	AnswerHis string `json:"answer_his" xorm:"not null comment('做题历史信息') VARCHAR(4096)"`
}
var userquestion ="user_question"

func(uq *UserQuestion) GetRow() bool {
	var ids []int
	 mEngine.Table(userquestion).Where("user_id=?",uq.UserId).
		Where("question_id=?",uq.QuestionId).Cols("id").Find(&ids)

	if len(ids)>=1  {
		return true
	}
	return false
}

func(uq *UserQuestion)  ListTestStatus() ([]UserQuestion,error) {
	var userQuestions []UserQuestion
	err:= mEngine.Table(userquestion).Where("user_id=?",uq.UserId).
	Where("question_id=?",uq.QuestionId).Find(&userQuestions)

	return userQuestions,err
}
func(uq *UserQuestion)  UpdateTestStatus(imgIds[] string) error {
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}

	if uq.TestStatus==0{

		if _, err := mEngine.Exec("delete from "+userquestion+" where user_id=? and question_id =? " ,uq.UserId,uq.QuestionId); err != nil {
			return err
		}

		//删除图片使用情况
		if _, err := mEngine.Exec("delete from "+useranswerimage+" where user_id=? and question_id =? " ,uq.UserId,uq.QuestionId); err != nil {
			return err
		}


	} else{
		if uq.GetRow() {
			//删除图片使用情况
			if _, err := mEngine.Exec("delete from "+useranswerimage+" where user_id=? and question_id =? " ,uq.UserId,uq.QuestionId); err != nil {
				return err
			}

			if _, err := mEngine.Exec("update "+userquestion+" set test_status=? , answer_his=? where user_id=? and question_id =? " ,
				uq.TestStatus,uq.AnswerHis,uq.UserId,uq.QuestionId); err != nil {
				return err
			}


		}else{

			if _,err:=session.Insert(uq); err!=nil{
				return err
			}
		}




		//数组变成集合，去重
		var imgIdSet = make(map[string]string) //make定义
		for _,imgId:=range imgIds {
			imgIdSet[imgId]=imgId
		}

		for imgId, _ := range imgIdSet{
			userAnswerImageModel := UserAnswerImage{UserId:uq.UserId ,QuestionId: uq.QuestionId, ImgId: imgId}

			has, err := session.Get(&userAnswerImageModel)
			if err != nil {
				return  err
			}
			//如果答案图片记录不存在，添加问题图片记录
			if !has {
				_, err = session.Insert(&userAnswerImageModel)
				if err != nil {
					return err
				}
			}
		}


	}

	return session.Commit()


}
